<?php

namespace App\Common\Tools;

use \Auth;

class Emchat
{
    public $client_id = 'YXA6MjIYvsa5Q8uxUqbcCwsTzQ';
    public $client_secret = 'YXA6iqTmbBDG_3F7e3HRfRK3siMMgGc';
    public $org_name = '1104191203042059';
    public $app_name = 'loveforever';

    /**
     *获取token
     */
    public function getToken()
    {
        //将外面的变量变成全局

        $options = array(
            "grant_type" => "client_credentials",
            "client_id" => $this->client_id,
            "client_secret" => $this->client_secret
        );
        //json_encode()函数，可将PHP数组或对象转成json字符串，使用json_decode()函数，可以将json字符串转换为PHP数组或对象
        $body = json_encode($options);
        //使用 $GLOBALS 替代 global
        $url = 'https://a1.easemob.com/' . $this->org_name . '/' . $this->app_name . '/token';
        //$url=$base_url.'token';
        $tokenResult = self::postCurl($url, $body);
        //var_dump($tokenResult['expires_in']);
        //return $tokenResult;

        $token  = "Authorization:Bearer " . $tokenResult['res']["access_token"];
//        return $this->successReturn(['token'=>$token]);

        return $token;
    }

    /**
     * 授权注册
     */
    function createUser($user_id)
    {
        $url = 'https://a1.easemob.com/' . $this->org_name . '/' . $this->app_name . '/users';
        $username = $user_id;
        $password = md5(md5($username.'HJl598jsIJDk78H'));
        $options = array(
            "username" => $username,
            "password" => $password
        );
        $body = json_encode($options);
        $header = array(self::getToken());
        $result = self::postCurl($url, $body, $header);
        if($result['httpCode'] == 200){
            return $password;
        }else{
            return false;
        }
    }

    /**
     * 加好友
     */
    function contacts($user_id , $friend_id)
    {
        $url = 'https://a1.easemob.com/' . $this->org_name . '/' . $this->app_name . '/users/' . $user_id . '/contacts/users/'.$friend_id;
        $options = array();
        $body = json_encode($options);
        $header = array(self::getToken());
        $result = self::postCurl($url, $body, $header);
        if($result['httpCode'] == 200){
            return true;
        }else{
            return false;
        }
    }

    /**
     * 发消息
     */
    function messages($user_id , $from_id , $msg)
    {
        $url = 'https://a1.easemob.com/' . $this->org_name . '/' . $this->app_name . '/messages';
        $options = array(
            "target_type" => 'users',
            "target" =>  [$user_id],
            "msg" =>  ['type'=>'txt' , 'msg'=>$msg],
            "from" =>  $from_id,

        );
        $body = json_encode($options);
        $header = array(self::getToken());
        $result = self::postCurl($url, $body, $header);
        if($result['httpCode'] == 200){
            return true;
        }else{
            return false;
        }
    }

    /**
     *postCurl方法
     */
    function postCurl($url, $body, $header = null, $type = "POST")
    {
        //1.创建一个curl资源
        $ch = curl_init();
        //2.设置URL和相应的选项
        curl_setopt($ch, CURLOPT_URL, $url);//设置url
        //1)设置请求头
        //array_push($header, 'Accept:application/json');
        //array_push($header,'Content-Type:application/json');
        //array_push($header, 'http:multipart/form-data');
        //设置为false,只会获得响应的正文(true的话会连响应头一并获取到)
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_TIMEOUT, 5); // 设置超时限制防止死循环
        //设置发起连接前的等待时间，如果设置为0，则无限等待。
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
        //将curl_exec()获取的信息以文件流的形式返回，而不是直接输出。
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        //2)设备请求体
        $body = json_decode($body , true);
        if (count($body) > 0) {
            //$b=json_encode($body,true);
//            var_dump(1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body));//全部数据使用HTTP协议中的"POST"操作来发送。
        }
        //设置请求头
        if(!empty($header)){
            if (count($header) > 0) {
                curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
            }
        }
        //上传文件相关设置
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_MAXREDIRS, 3);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);// 对认证证书来源的检查
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);// 从证书中检查SSL加密算

        //3)设置提交方式
        switch ($type) {
            case "GET":
                curl_setopt($ch, CURLOPT_HTTPGET, true);
                break;
            case "POST":
                curl_setopt($ch, CURLOPT_POST, true);
                break;
            case "PUT"://使用一个自定义的请求信息来代替"GET"或"HEAD"作为HTTP请									                     求。这对于执行"DELETE" 或者其他更隐蔽的HTT
                curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
                break;
            case "DELETE":
                curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
                break;
        }
        //4)在HTTP请求中包含一个"User-Agent: "头的字符串。-----必设
        curl_setopt($ch, CURLOPT_USERAGENT, 'SSTS Browser/1.0');
        curl_setopt($ch, CURLOPT_ENCODING, 'gzip');
        curl_setopt ( $ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0)' ); // 模拟用户使用的浏览器
        //5)


        //3.抓取URL并把它传递给浏览器
        $res=curl_exec($ch);
        $httpCode = curl_getinfo($ch,CURLINFO_HTTP_CODE);
        $result=json_decode($res,true);
        //4.关闭curl资源，并且释放系统资源
        curl_close($ch);
        if(empty($res)){
            $res = array('res'  => $res , 'httpCode'  => $httpCode);
            return $res;
        } else {
            $result = array('res'  => $result , 'httpCode'  => $httpCode);
            return $result;
        }
    }



}